/**
 * 
 */
package com.changil.nowonchangilchurch.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.content.Context;

import com.changil.nowonchangilchurch.R;

/**
 * @author zeropol2
 *
 */
public class DateUtil {

	public static String getPublishDate(Context context, Date publishDate) {
		String result = null;
		Date nowDate = new Date();
		Calendar nowCalendar = Calendar.getInstance();
		nowCalendar.setTime(nowDate);
		Calendar publishCalendar = Calendar.getInstance();
		publishCalendar.setTime(publishDate);
		long timeSpace = nowDate.getTime() - publishDate.getTime();
		if(1 > timeSpace/ 1000 / 60) {	//1분 미만
			result = context.getResources().getString(R.string.common_just_before);
		} else if(60 > timeSpace/ 1000 / 60) {	//1시간 미만
			result = String.format(context.getResources().getString(R.string.common_minute_ago), timeSpace/ 1000 / 60);
		} else if(24 > timeSpace / 1000 / 60 / 60) {	//24시간 미만
			result =  String.format(context.getResources().getString(R.string.common_hour_ago), timeSpace/ 1000 / 60 / 60);
		} else if(nowCalendar.get(Calendar.YEAR) == publishCalendar.get(Calendar.YEAR)) {	//같은 년도 꺼면
			SimpleDateFormat format = new SimpleDateFormat("M"+context.getResources().getString(R.string.common_month) 
					+ " d"+context.getResources().getString(R.string.common_day)+ " a h:mm");
			result = format.format(publishDate);
		} else {
			SimpleDateFormat format = new SimpleDateFormat("yyyy"+context.getResources().getString(R.string.common_year)
					+" M"+context.getResources().getString(R.string.common_month)
					+" d"+context.getResources().getString(R.string.common_day) );
			result = format.format(publishDate) ;
		}
		return result;
	}

	/**
	 * 두 Date의 년월일 까지만을 비교한다
	 *
	 * @param date1
	 * @param date2
	 * @return 년월일이 같다면 true, 그 외는 false
	 */
	public static boolean compareOnlyDate(Date date1, Date date2){

		if ( date1 != null && date2 != null ){
			Calendar calendar1 = Calendar.getInstance();
			Calendar calendar2 = Calendar.getInstance();
			calendar1.setTime(date1);
			calendar2.setTime(date2);

			return ( calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR)
					&& calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH)
					&& calendar1.get(Calendar.DATE) == calendar2.get(Calendar.DATE) );
		}

		return false;
	}

	public static String getThisSundayYYYYMMDD() {
		Calendar cal = Calendar.getInstance();
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
	    cal.add(Calendar.DATE, ( Calendar.SUNDAY -cal.get ( Calendar.DAY_OF_WEEK) ) );
	    Date date = cal.getTime();
	    return formatter.format(date);
	}
	
	public static String getLastSundayYYYYMMDD() {
		Calendar cal = Calendar.getInstance();
	    SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
	    cal.add(Calendar.DATE, ( Calendar.SUNDAY -cal.get ( Calendar.DAY_OF_WEEK) ) - 7);
	    Date date = cal.getTime();
	    return formatter.format(date);
	}
}
